import {
	floatOpration
} from '../../utils/util.js'
import {
	request
} from '../../utils/request.js'
const multi = floatOpration.multi;
const add = floatOpration.add;
let app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		list: [],
		selectFoods: [],
		selectFood: [],
		navActive: 0,
		heightArr: [],
		containerH: 0,
		totalMoeny: 0,
		totalCount: 0,
		closeShadow: false,
		showDetails: false,
		list: [],
		list2: [],
		type: 1,
		leftId: '',
		showType: true,
		keyWord: '',
		leftData: [],
		topData: [],
		goodsData: [],
		height: 0,
		cate1: 1,
		typeFlag: 1, //1初始化 2左边 3顶部
		active: 0 
	},
	onLoad: function (options) {
		wx.getSystemInfo({
			success: res => {
				let clientHeight = res.windowHeight;
				let clientWidth = res.windowWidth;
				let ratio = 750 / clientWidth;
				let height = clientHeight * ratio;
				this.setData({
					height: height - 250
				});
			}
		});
		this.setData({
			navActive: 0,
			leftId: 28
		})

    console.log(this.data.leftId)

    // this.init();
	},
	// 直接下单

	toPay() {
		let newCar = []
		request({
			url: `goodsList`,
			token: wx.getStorageSync('token'),
			method: 'POST',
		}).then(res => {
			let data = res.data.data.type1.goodsData
			let datas = data.concat(res.data.data.type2.goodsData)
			datas.forEach(item => {
				if (item.number != 0) {
					newCar.push(item)
				}
			})

			console.log('处理之后的数据', newCar.length)
			if (newCar.length == 0) {
				wx.showModal({
					title: '提示', //提示的标题,
					content: '请选择商品后再下单', //提示的内容,
					showCancel: false, //是否显示取消按钮,

				});
			} else {
				// 0: { id: 54, name: "金龙鱼盘锦大米5KG", type: "米面粮油_米", thumb: "/upload/admin/20200418/064ebd9b6db057c6f1a372706b29db04.png", market_price: "100.00", … }
				wx.navigateTo({
					url: `/pages/pay/pay?orderInfo=${JSON.stringify(newCar)}`
				})
			}
		})


	},
	add(e) {
		console.log('新增--------', e)
		let typeFlag = this.data.typeFlag
		console.log(typeFlag)
		let goodId = e.currentTarget.dataset.goodid
		let number = this.data.goodsData.find(item => item.id == goodId).number
		// console.log('number', number + 1)
		request({
			url: `setNum`,
			token: wx.getStorageSync('token'),
			method: 'POST',
			data: {
				productId: goodId,
				number: number + 1
			}
		}).then(res => {

      //console.log(typeFlag)

			if (typeFlag == 1) {
				this.init()
			} else if (typeFlag == 2) {
				this.leftSelect()
			} else if (typeFlag == 3) {
				this.topSelect()
      } else if (typeFlag == 4) {
        this.searchGoods()
      }
      
			let allNums = 0
			this.data.goodsData.forEach(item => {
				allNums = allNums + item.number
			})
			wx.setStorageSync("cartNumber", allNums)
		})
		setTimeout(() => {
			// 更新完数据在加入购物车
			let selectFoods = this.data.selectFoods
			let selectFood = this.data.goodsData.find(item => item.id == goodId)
			selectFoods.push(selectFood)
			wx.setStorageSync("cartNumber", selectFoods.length)
      console.log(selectFoods.length)
			wx.setStorageSync("cart", selectFoods)
			// selectFoods.forEach((item, index) => {})
			this.setData({
				selectFoods
			})
			console.log(selectFoods)
		}, 500)
	},
	minus(e) {

		let typeFlag = this.data.typeFlag
		let goodId = e.currentTarget.dataset.goodid
		let selectFood = this.data.goodsData.find(item => item.id == goodId)
		let number = this.data.goodsData.find(item => item.id == goodId).number
		console.log('number', number - 1)
		if (number <= 0) {
			return
		}
		request({
			url: `setNum`,
			token: wx.getStorageSync('token'),
			method: 'POST',
			data: {
				productId: goodId,
				number: number - 1
			}
		}).then(res => {
			if (typeFlag == 1) {
				this.init()
			} else if (typeFlag == 2) {
				this.leftSelect()
			} else if (typeFlag == 3) {
				this.topSelect()
      } else if (typeFlag == 4) {
        this.searchGoods()
      }

		})
	},

	onChange(e) {
		this.setData({
			keyWord: e.detail
		});
	},
	searchGoods(e) {
		request({
			url: `searchGoods`,
			token: wx.getStorageSync('token'),
			method: 'POST',
			data: {
				type: this.data.type,
				search: this.data.keyWord
			}
		}).then(res => {
			let data = res.data.data
      console.log(data)
			this.setData({
				leftData: data.leftData,
				topData: data.topData,
				goodsData: data.goodsData,
				// leftId: this.data.leftId
				active:0,
        typeFlag:4,
        navActive: 0,
        leftId: 28
			})

			data.goodsData.forEach(item => {
				this.setData({
					// leftId: item.cate1_id,
					topId: item.cate2_id
				})
			})

      app.scanCart()
			// this.init()
			// this.leftSelect()
		})
	},
	init() {
    const topId = 29
    const leftId = 28
		wx.setStorageSync('selectType', 1);
		console.log('再次进入的时候', this.data.cate1)
		request({
      url: `goodsList?type=${this.data.type}&cate1=${leftId}&cate2=${topId}`,
			// url: `goodsList`,
			token: wx.getStorageSync('token'),
			// data:{
			// 	type:this.data.type
			// },
			method: 'POST',
		}).then(res => {
			let data = res.data.data
			data.goodsData.forEach(item => {
				item.count = 1
			})
			this.setData({
				leftData: data.leftData,
				topData: data.topData,
				goodsData: data.goodsData,
				active: 0
			})

			console.log('init执行')
			let allNums = 0
			this.data.goodsData.forEach(item => {
				allNums = allNums + item.number
			})


      this.setData({
        navActive: 0
      })

			wx.setStorageSync("cartNumber", (allNums))
			app.scanCart()
		})
	},

	leftSelect(e) {
		console.log('leftSelect++++++++++++', e)
		if (e) {
			this.setData({
				leftId: e.currentTarget.dataset.id1,
				navActive: e.currentTarget.dataset.index,
				active: 0,
				typeFlag: 2
			})
			if (e.currentTarget.dataset.index == 0) {
				this.setData({
					leftId: this.data.leftId
				})
			}
		}
		// console.log('11111111111', this.data.type, this.data)
		request({
			url: `goodsList?type=${this.data.type}&cate1=${this.data.leftId}`,
			// url: `goodsList`,
			token: wx.getStorageSync('token'),
			data: {
				type: this.data.type,
				// cate1:this.data.leftId
			},
			method: 'POST',
		}).then(res => {
			let data = res.data.data
			console.log('left的值---------', data)
			this.setData({
				leftData: data.leftData,
				topData: data.topData,
				goodsData: data.goodsData
			})
			let allNums = 0
			this.data.goodsData.forEach(item => {
				allNums = allNums + item.number
			})
			wx.setStorageSync("cartNumber", (allNums))
      console.log(wx.getStorageSync('cartNumber'))
			app.scanCart()
		})
	},

	topSelect(e) {
		if (e) {
			let title = e.detail.title;
			const topId = this.data.topData.find(item => item.name == title).id
			this.setData({
				topId,
				typeFlag: 3
			})
		}
		request({
			url: `goodsList?type=${this.data.type}&cate1=${this.data.leftId}&cate2=${this.data.topId}`,
			token: wx.getStorageSync('token'),
			method: 'POST',
		}).then(res => {
			let data = res.data.data
			this.setData({
				leftData: data.leftData,
				topData: data.topData,
				goodsData: data.goodsData
			})
			let allNums = 0
			this.data.goodsData.forEach(item => {
				allNums = allNums + item.number
			})
			wx.setStorageSync("cartNumber", (allNums))
      
			app.scanCart()
		})
	},

  // 缩略图懒加载
  onPageScroll(){
    console.log('scroll')
    this.showImg()
  },
  showImg(){
    let height = this.data.height
    console.log(height)
    let goodsData = this.data.goodsData
    wx.createSelectorQuery().selectAll('.item').boundingClientRect((ret)=>{
      ret.forEach((item,index)=>{
        if(item.top<=height){
          goodsData[index].show = true
        }
      })

      this.setData({
        goodsData
      })


    })


    console.log(this.data.goodsData)
  },

	toGoodDetails(e) {
		let id = e.currentTarget.dataset.id;
    
    wx.navigateTo({
			url: `/pages/foodsDetail/foodsDetail?id=${id}`
		})
	},

	// ---------------------------------------------------------------------------------------

	closeShadow() {
		this.setData({
			closeShadow: false
		})
	},

	showCartList() {
		if (this.data.selectFoods.length) {
			this.setData({
				closeShadow: true
			})
		}
	},

	//清空购物车
	clearShopCart() {
		let data = this.data.list;
		let goods = this.data.selectFoods;

		let typeOneIndex, goodIndex;
		for (let i = 0; i < goods.length; i++) {
			typeOneIndex = goods[i].typeOneIndex;
			goodIndex = goods[i].goodIndex;
			data[typeOneIndex].goods[goodIndex].count = 0;
			data[typeOneIndex].typeItemCount = 0;
		}

		this.setData({
			selectFoods: [],
			list: this.data.list,
			totalMoney: 0,
			totalCount: 0
		})
	},





	//选择商品
	onStepperEvent(e) {
		console.log(e)
		let {
			typeOneIndex,
			goodIndex,
			goodId,
			xsNum,
			goodOne,
			goodCount
		} = e.detail
		let {
			list,
			selectFoods
		} = this.data
		console.log(list)
		console.log(selectFoods)
		let typeGood = list[typeOneIndex]
		let good = list[typeOneIndex].goods[goodIndex]
		let itemCount = 0
		//添加自定义属性购物车ckbox按钮选择用selected
		list[typeOneIndex].goods[goodIndex].selected = false
		//在这里改变自定义count的值
		list[typeOneIndex].goods[goodIndex].count = goodCount
		typeGood.goods.forEach((good) => {
			itemCount += good.count || 0
		})
		//添加属性要传的属性
		typeGood.typeItemCount = itemCount

		good.typeOneIndex = typeOneIndex;
		good.goodIndex = goodIndex;
		if (selectFoods.includes(good)) {
			let index = selectFoods.indexOf(good)
			// 当前商品为0是清空
			goodCount === 0 ? selectFoods.splice(index, 1) : selectFoods[index].count = goodCount
		} else {
			selectFoods.push(good)
		}
		this.setData({
			list,
			selectFoods
		})
		this.calculateMoney(selectFoods)
		wx.setStorageSync("cart", selectFoods) //购物车数据

	},

	/*计算价格和总数量*/
	calculateMoney(selectFoods) {
		let totalMoney = 0;
		let totalCount = 0;
		let price = 0;
		for (let i = 0; i < selectFoods.length; i++) {
			price = Number(selectFoods[i].money);
			totalMoney = add(totalMoney, multi(price, selectFoods[i].count));
			totalCount += selectFoods[i].count;
		}
		this.setData({
			totalMoney,
			totalCount
		});
		console.log('计算cartNumber', totalCount);
		wx.setStorageSync("cartNumber", totalCount) //tabbar数字


	},

	//右边滚动联动
	onScroll(e) { },


	onReady: function () {
	},
	onHide: function () {
    

    // wx.navigateTo({
    //   url: 'B?id=1'
    // })
    
	},
	onShow: function () {
		this.setData({
			showType: true,
			// navActive: 0,
      leftId: this.data.leftId,
      //typeFlag:1
		})
    if(this.data.typeFlag==4){
      this.setData({
        typeFlag:1
      })
    }

    if (!wx.getStorageSync('repair')){
      this.setData({
        leftId:28
      })
      this.init()
    }
    else{
      wx.removeStorageSync("repair");
    }

    console.log(this.data.leftId)
		
	},
	onUnload: function () { 
    


  },
	onPullDownRefresh: function () {

	},
	onReachBottom: function () {

	},
	onShareAppMessage: function () {

	},
	closeShowDetails: function () {
		this.setData({
			showDetails: !this.data.showDetails
		});
	},
	showDetails: function (e) {
		const descImg = e.currentTarget.dataset.img;
		this.setData({
			descImg,
			showDetails: true
		});
	}
})
